//
//  NSString+HBExtension.m
//  HBActionSheet
//
//  Created by 韩冰 on 2017/10/24.
//  Copyright © 2017年 韩冰. All rights reserved.
//

#import "NSString+HBExtension.h"
#import <CommonCrypto/CommonDigest.h>

#define EmojiCodeToSymbol(c) ((((0x808080F0 | (c & 0x3F000) >> 4) | (c & 0xFC0) << 10) | (c & 0x1C0000) << 18) | (c & 0x3F) << 24)
@implementation NSString (HBExtension)

- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    if (self == nil) return CGSizeZero;
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    CGSize size = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    return CGSizeMake(ceilf(size.width), ceilf(size.height));
}

- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW maxH:(CGFloat)maxH
{
    if (self == nil) return CGSizeZero;
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, maxH);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithFont:font maxW:MAXFLOAT];
}


// emoji
+ (NSString *)emojiWithIntCode:(long)intCode
{
    long symbol = EmojiCodeToSymbol(intCode);
    NSString *string = [[NSString alloc] initWithBytes:&symbol length:sizeof(symbol) encoding:NSUTF8StringEncoding];
    if (string == nil) { // 新版Emoji
        string = [NSString stringWithFormat:@"%C", (unichar)intCode];
    }
    return string;
}

- (NSString *)emoji
{
    return [NSString emojiWithStringCode:self];
}

+ (NSString *)emojiWithStringCode:(NSString *)stringCode
{
    char *charCode = (char *)stringCode.UTF8String;
    long intCode = strtol(charCode, NULL, 16);
    return [self emojiWithIntCode:intCode];
}

// 判断是否是 emoji表情
- (BOOL)isEmoji
{
    BOOL returnValue = NO;
    
    const unichar hs = [self characterAtIndex:0];
    // surrogate pair
    if (0xd800 <= hs && hs <= 0xdbff) {
        if (self.length > 1) {
            const unichar ls = [self characterAtIndex:1];
            const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
            if (0x1d000 <= uc && uc <= 0x1f77f) {
                returnValue = YES;
            }
        }
    } else if (self.length > 1) {
        const unichar ls = [self characterAtIndex:1];
        if (ls == 0x20e3) {
            returnValue = YES;
        }
    } else {
        // non surrogate
        if (0x2100 <= hs && hs <= 0x27ff) {
            returnValue = YES;
        } else if (0x2B05 <= hs && hs <= 0x2b07) {
            returnValue = YES;
        } else if (0x2934 <= hs && hs <= 0x2935) {
            returnValue = YES;
        } else if (0x3297 <= hs && hs <= 0x3299) {
            returnValue = YES;
        } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
            returnValue = YES;
        }
    }
    
    return returnValue;
}

- (BOOL)isContainsEmoji
{
    __block BOOL isEomji = NO;
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        const unichar hs = [substring characterAtIndex:0];
        // surrogate pair
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    isEomji = YES;
                }
            }
        } else {
            // non surrogate
            if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                isEomji = YES;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                isEomji = YES;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                isEomji = YES;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                isEomji = YES;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                isEomji = YES;
            }
            if (!isEomji && substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                if (ls == 0x20e3) {
                    isEomji = YES;
                }
            }
        }
    }];
    return isEomji;
}

- (NSInteger)calculateTextNumber
{
    NSInteger i, n = [self length], l = 0, a = 0, b = 0;
    unichar c;
    for(i = 0; i < n; i++)
    {
        c = [self characterAtIndex:i];
        if (isblank(c))
        {
            b++;
        } else if (isascii(c))
        {
            a++;
        }
        else
        {
            l++;
        }
    }
    if(a == 0 && l == 0) return 0;
    return l+(int)ceilf((float)(a+b)/2.0);
}

- (NSString *)stringNumToWan
{
    NSString *returnStr = @"";
    if (self.length && [self integerValue] > 0)
    {
        NSInteger num = [self integerValue];
        if (num > 10000)
        {
            returnStr = [NSString stringWithFormat:@"%ld.%ld万", num / 10000, num % 10000 / 1000];
        }
        else if (num > 9999999)
        {
            returnStr = [NSString stringWithFormat:@"999万＋"];
        }
        else
        {
            returnStr = self;
        }
    }
    return returnStr;
}
- (BOOL)isBlank{
    if (self == nil || self == NULL || [self isKindOfClass:[NSNull class]] || [self length] == 0 || [self isEqualToString: @"(null)"]) {
        return YES;
    }
    return NO;
}
- (NSString *)md5String
{
    const char *ptr = [self UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(ptr, (CC_LONG)strlen(ptr), md5Buffer);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", md5Buffer[i]];
    }
    
    return [output copy];
}

- (CGFloat)stringHeightWithFont:(UIFont *)font width:(CGFloat)width{
    CGSize size = CGSizeMake(width, CGFLOAT_MAX);
    
    
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    //    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    //    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    //    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    size =[self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size.height;
}

-(NSDictionary *)jsonStringToDictionary
{
    if (self == nil) {
        return nil;
    }
    
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    //    BOOL  isJson=[NSJSONSerialization isValidJSONObject:self];
    //    NSArray *arr=[NSArray arrayWithObject:jsonData];
    //    id json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&err];
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

//去除字符串
-(NSString *)htmlToString
{
    if (self == nil) {
        return nil;
    }
    NSString *html=self;
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
    
}


-(NSString *)base64StringFromText
{
    NSData *nsdata = [self
                      dataUsingEncoding:NSUTF8StringEncoding];
    
    // Get NSString from NSData object in Base64
    NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
    
    // Print the Base64 encoded string
    return  base64Encoded;
}

-(NSString *)textFromBase64String
{
    NSData *nsdataFromBase64String = [[NSData alloc]
                                      initWithBase64EncodedString:self options:0];
    
    // Decoded NSString from the NSData
    NSString *base64Decoded = [[NSString alloc]
                               initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    return base64Decoded;
    
}
-(NSURL *)macUrl{
    return  [NSURL URLWithString:self];
}
-(UIImage *)macImage{
    return [UIImage imageNamed:self];
}
- (NSMutableAttributedString *)getAttributedTextWithFont:(CGFloat )font withTextColor:(UIColor *)color withImage:(UIImage *)image withImageBounds:(CGRect)bound{
    
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image = image;
    attach.bounds = bound;
    NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@" %@",self]];
    [str addAttributes:@{
                         NSFontAttributeName :[UIFont systemFontOfSize:font],
                         NSForegroundColorAttributeName :color
                         
                         } range:NSMakeRange(0, self.length + 1)];
    
    
    NSMutableAttributedString *textAttr=[[NSMutableAttributedString alloc]init];
    [textAttr appendAttributedString:attachString];
    [textAttr appendAttributedString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    [textAttr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, textAttr.length)];
    return textAttr;
}


@end


@implementation NSString (Date)

@end

@implementation NSMutableAttributedString (HBExtension)

- (NSMutableAttributedString *)stringWithParagraph{
    
    return  [self stringWithParagraphSpace:5];;
}
- (NSMutableAttributedString *)stringWithParagraphSpace:(CGFloat)space{
    
    if (self == nil) {
        return nil;
    }
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    //行间距
    paragraph.lineSpacing = space;
    //对齐方式
    paragraph.alignment = NSTextAlignmentLeft;
    [self addAttribute:NSParagraphStyleAttributeName
                 value:paragraph
                 range:NSMakeRange(0, self.length)];
    
    return self;
}


@end
